import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
import Login from '../views/Login.vue'
import Main from '../views/Main.vue'
import {useAuthStore} from '../stores/auth'
import DataVisualization from "../views/DataVisualization.vue";
import Settings from "../views/Settings.vue";
import ContentArea from "../views/ContentArea.vue";

const routes:RouteRecordRaw[] = [
    {
        path: '/', redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {title: '用户登录'}
    },
    {
        path: '/main',
        name: 'Main',
        component: Main,
        meta: {
            requiresAuth: true,
            title: '主界面'
        },
        children: [
            {
                path: '', // 默认子路由
                name: 'Dashboard',
                component: ContentArea, // 创建仪表板组件
                meta: { title: '仪表板' }
            },
            {
                path: '/data',
                name: 'Data',
                component: DataVisualization,
                meta: {
                    requiresAuth: true,
                    title: '数据分析'
                }
            },
            {
                path: '/settings',
                name: 'Settings',
                component: Settings,
                meta: {
                    requiresAuth: true,
                    title: '系统设置'
                }
            }
        ]
    },

]

const router = createRouter({
    history: createWebHashHistory(),
    routes:routes
})
router.beforeEach((to, from, next) => {
    console.log('[路由守卫] 开始导航', {
        from: from.path,
        to: to.path,
        requiresAuth: to.meta.requiresAuth,
        isAuthenticated: useAuthStore().isAuthenticated
    })

    const authStore = useAuthStore()
    const allowList = ['/login']

    if (to.meta.requiresAuth) {
        if (!authStore.isAuthenticated) {
            next({ path: '/login', query: { redirect: to.fullPath } })
        } else {
            next()
        }
    } else {
        if (allowList.includes(to.path) && authStore.isAuthenticated) {
            window.electronAPI.invoke('resize-window',{ width: 1920, height: 1080 })
            next('/main')
        } else {
            next()
        }
    }
})

export default router
